﻿//udp服务端
//udp通信可以使用udp和udpClient,后者是对socket的封装


using System.Net;
using System.Net.Sockets;
using System.Text;

//声明udp服务
//Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
////声明服务端的端口并绑定
//server.Bind(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 6001));
////打印服务端开启消息
//Console.WriteLine("服务端已开启");
////服务端开启接收消息进程
//Thread t = new Thread(() => ReceiveMsg(server));
//t.Start();
////服务端开启发送消息进程
//Thread t2 = new Thread(() => SendMsg(server));
//t2.Start();

////发送消息
//void SendMsg(Socket server)
//{
//    //死循环发送消息
//    while (true)
//    {
//        //声明发送端ip和端口
//        EndPoint point = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 6000);

//        //获取键盘输入
//        string msg = Console.ReadLine();

//        //发送消息
//        server.SendTo(Encoding.UTF8.GetBytes(msg), point);
//    }
//}

////接收消息
//void ReceiveMsg(Socket server)
//{
//    //死循环接收消息
//    while (true)
//    {
//        //声明接收哪个客户端的
//        EndPoint point = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 6000);

//        //声明接收缓冲区
//        byte[] buffer = new byte[1024];

//        //接收字节信息
//        int length = server.ReceiveFrom(buffer, ref point);

//        //将字节数转为字符串
//        string message = Encoding.UTF8.GetString(buffer, 0, length);

//        //打印输出消息
//        Console.WriteLine($"收到了消息:{message}");
//    }
//}



//使用udpclient发送消息
UdpClient udpClient = new UdpClient(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 9300));
Console.WriteLine("udp服务端已开启");

Thread t = new Thread(() => ReciveMsg(udpClient));
t.Start();

Thread t2 = new Thread(() => SendMsg(udpClient));
t2.Start();

void SendMsg(UdpClient udpClient)
{
    while (true)
    {
        IPEndPoint point = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 9301);
        var message = Console.ReadLine();
        var data = Encoding.UTF8.GetBytes(message);
        udpClient.Send(data, data.Length, point);
    }
}




void ReciveMsg(UdpClient udpClient)
{
    while (true)
    {
        IPEndPoint point = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 9301);
        var data = udpClient.Receive(ref point);
        string message = Encoding.UTF8.GetString(data, 0, data.Length);
        Console.WriteLine($"接收了消息:{message}");
    }
}